<template>
  <header class="h-16 border-b border-gray-700">
    <nav class="max-w-7xl mx-auto h-full flex items-center justify-between px-4">
      <div class="text-2xl font-['Pacifico']">Jake</div>
      <div class="flex space-x-8">
        <button v-for="tab in tabs"
                :key="tab.id"
                :class="['px-4 py-2 !rounded-button border-indigo-500/50 whitespace-nowrap hover:text-primary',
                          { 'tab-active': currentTab === tab.id }]"
                @click="changeTab(tab)">
          <i :class="[tab.icon, 'mr-2']"></i>{{ tab.name }}
        </button>
      </div>
      <div class="flex items-center space-x-4">
        <button class="bg-primary px-4 py-2 !rounded-button whitespace-nowrap" @click="onProfileRedirect">
          <i class="fas fa-user mr-2"></i>个人中心
        </button>
      </div>
    </nav>
  </header>
</template>
<script setup>
import {onMounted, ref} from "vue";
import { useRouter } from 'vue-router'
const prefix = 'ca-app'
const tabCacheKey = `${prefix}-currentTab`

const router = useRouter()
const currentTab = ref('');
const defaultTab = ref('chat')

onMounted(() => {
  const currentTabCache = localStorage.getItem(tabCacheKey)
  console.log(currentTabCache)

  let tab;
  let routePath;
  if (currentTabCache) {
    console.log('有缓存')
    tab = tabs.filter(tab => tab.id === currentTabCache)[0]
    routePath = tab['path']
    console.log(`cacheTabPath:   ${routePath}`)
  } else {
    console.log('走默认')
    tab = tabs.filter(tab => tab.id === defaultTab.value)[0]
    routePath = tab['path']
    console.log(`defaultTabPath:   ${routePath}`)
  }
  router.push(routePath)
  console.log(tab['id'])
  localStorage.setItem(tabCacheKey, tab['id'])
})

const tabs = [
  { id: 'home', name: '首页', path: '/home', icon: 'fas fa-home' },
  { id: 'chat', name: '聊天', path: '/chat', icon: 'fas fa-comments' },
  { id: 'explore', name: '探索', path: '/explore', icon: 'fas fa-compass' },
  { id: 'draw', name: '画图', path: '/draw', icon: 'fas fa-paint-brush' }
];

const changeTab = (tab) => {
  currentTab.value = tab.id;
  console.log(tab)
  console.log(router)
  router.push(currentTab.value)
  localStorage.setItem(tabCacheKey, currentTab.value)
}

const onProfileRedirect = () => {
  const currentTab = 'profile'
  router.push('/profile')
  localStorage.setItem(tabCacheKey, currentTab)
}
</script>
<style scoped>
</style>